<?php
// +----------------------------------------------------------------------
// author laobai
// +----------------------------------------------------------------------
// | Copyright (c) 2021 http://bbcweb.cn All rights reserved.
// +----------------------------------------------------------------------
namespace app\paiban\controller;

use think\admin\Controller;
use think\facade\Db;
use think\facade\Session;
class Index extends Controller
{
    public function login(){
        if($this->request->ispost())
        {
            $p=input();
            if(!empty($p['username']) && !empty($p['password']))
            {
                $user=Db::name('users')->where(['username'=>$p['username'],'password'=>$p['password']])->find();
                
                if($user)
                {
                    Session::set("user",$user);
                    $this->redirect('/paiban/index/index');
                }
            }
            $this->redirect('/paiban/index/login');
        }
        return $this->fetch();
    }
    public function index()
    {
        $admin=Session::get('user');
        if(empty($admin))
        {
            $this->redirect('/paiban/index/login');
            die;
        }
        if($admin['is_manager']==0 && $admin['is_admin']==0)
        {
            $this->redirect('/paiban/index/login');
            die;
        }
        $this->assign('admin',$admin);
        $map=array();
        $map[]=['bumen_id','=',$admin['bumen_id']];
        $user=Db::name('users')->where($map)->order('id desc')->select();
        $this->assign('user',$user);
        $banlei=Db::name('banlei')->order('id desc')->select();
        $this->assign('banlei',$banlei);
        return $this->fetch();
    }
    public function save()
    {
        $p=input();
        if($p['ban_date']=='')
        {
            $p['ban_date']=date('Y-m-d');
        }
        $ban_month=date('m',strtotime($p['ban_date']));
        $ban_day=date('d',strtotime($p['ban_date']));
        $p['ban_month']=$ban_month;
        $p['ban_day'] =$ban_day;
        $banci=$p['banci'];
        if($banci==4)
        {
            $p['banci']=1;
            $this->addBan($p);
            $p['banci']=2;
            $res = $this->addBan($p);
        }
        else
        {
            $res = $this->addBan($p);
        }
        if($res)
        {
            return $this->success('succ');
        }
        return $this->success('fail');
    }
    private function addBan($p)
    {
        $count=Db::name('ban')->where(['user_id'=>$p['user_id'],'ban_date'=>$p['ban_date'],'banci'=>$p['banci']])->count();
        if($count==0)
        {
            $p['add_time']=time();
            $res = Db::name('ban')->insert($p);
        }
        else {
            $res = Db::name('ban')->where(['user_id'=>$p['user_id'],'ban_date'=>$p['ban_date'],'banci'=>$p['banci']])->update(['mark'=>$p['mark'],'banci'=>$p['banci'],'banlei'=>$p['banlei']]);
        }
        return $res;
    }
}